<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model.trim="query.confLabel"
          clearable
          size="small"
          placeholder="输入配置名称搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-input
          v-model.trim="query.confName"
          clearable
          size="small"
          placeholder="输入配置英文标识搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <crudOperation show="" :permission="permission" />
    </div>
    <!--表单渲染-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      title="新增数据源配置"
      width="55%"
    >
      <el-form ref="form" :inline="true" label-position="left" :model="form" :rules="rules" size="small" label-width="120px">
        <el-form-item label="数据源类型" prop="confType">
          <el-select
            v-model="form.confType"
            filterable
            clearable
            placeholder="请选择"
            style="width: 100%"
            @change="changeConfType"
          >
            <el-option
              v-for="item in dict.source_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配置英语标识" prop="confName" style="margin-left: 80px">
          <el-input v-model.trim="form.confName" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="校验规则" prop="verifyRules">
          <el-select v-model="form.verifyRules" clearable placeholder="请选择">
            <el-option
              v-for="item in dict.verify_rules"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="配置名称" prop="confLabel" style="margin-left: 80px">
          <el-input v-model.trim="form.confLabel" maxlength="100" show-word-limit />
        </el-form-item>
        <el-row>
          <el-form-item label="输入类型" prop="valueType">
            <el-radio-group v-model="form.valueType">
              <el-radio
                v-for="item in dict.source_conf_value_type"
                :key="item.value"
                :label="item.value"
                style="margin-left: 5px"
              >{{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row v-if="form.valueType === 'SELECT' || form.valueType === 'RADIO'">
          <el-form-item label="选择数据值" prop="selectValues">
            <el-input
              v-model="form.selectValues"
              placeholder="必须按照指定格式输入选项值，格式[{text:'',value:''},{text:'',value:''}]"
              type="textarea"
              style="width: 610px;"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="属性选择" prop="isMain">
            <div>
              <el-checkbox
                v-model="form.isMain"
                label="是否是主配置"
                true-label="Y"
                false-label="N"
              />
              <el-checkbox
                v-model="form.isRelevance"
                label="是否关联某个配置"
                true-label="Y"
                false-label="N"
              />
            </div>
            <div>
              <el-checkbox
                v-model="form.isShow"
                label="是否允许编辑"
                true-label="Y"
                false-label="N"
              />
              <el-checkbox
                v-model="form.isPlaceholderAttribute"
                label="是否是占位符属性"
                true-label="Y"
                false-label="N"
              />
            </div>
          </el-form-item>
        </el-row>
        <el-row v-if="form.isRelevance === 'Y'">
          <el-form-item label="关联属性名称" prop="relevanceConfName">
            <el-select v-model="form.relevanceConfName" placeholder="请选择" style="width: 100%" @change="changeRelevanceConfName">
              <el-option
                v-for="item in assAttrList"
                :key="item.confName"
                :label="item.confLabel"
                :value="item.confName"
              >
                <span style="float: left">{{ item.confLabel }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.confName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row v-if="form.isRelevance === 'Y'">
          <el-form-item label="关联属性值" prop="relevanceConfValue">
            <el-select v-model="form.relevanceConfValue" :multiple="true" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in attributeValue"
                :key="item.value"
                :label="item.text"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row v-if="form.isPlaceholderAttribute === 'Y'">
          <el-form-item label="替换属性名称" prop="placeholderConfName">
            <el-select v-model="form.placeholderConfName" placeholder="请选择" style="width: 100%">
              <el-option
                v-for="item in assAttrList"
                :key="item.confName"
                :label="item.confLabel"
                :value="item.confName"
              >
                <span style="float: left">{{ item.confLabel }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.confName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="排序值" prop="showSort">
            <el-input-number v-model.number="form.showSort" :min="1" :max="100" controls-position="right" style="width: 200px;" />
          </el-form-item>
          <el-form-item label="配置默认值" prop="confValue" style="margin-left: 100px">
            <el-input v-model="form.confValue" maxlength="200" show-word-limit />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="配置描述" prop="confDes">
            <el-input
              v-model="form.confDes"
              type="textarea"
              show-word-limit
              maxlength="100"
              style="width: 380px;"
            />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>

    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%;"
      @selection-change="crud.selectionChangeHandler"
      @row-dblclick="rowDbclick"
      @filter-change="crud.handleFilterChange"
    >
      <el-table-column type="selection" />
      <el-table-column
        v-if="columns.visible('confType')"
        key="confType"
        label="数据源类型"
        :show-overflow-tooltip="true"
        prop="confType"
        :filters="filterConfTypeDict"
        filter-placement="bottom-end"
        :filter-multiple="false"
        column-key="confType"
        :filter-method="filterConfType"
        min-width="150"
      >
        <template slot-scope="scope">
          {{ confTypeFormatter(scope.row.confType) }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('confLabel')"
        :show-overflow-tooltip="true"
        prop="confLabel"
        label="配置名称"
        min-width="150"
      />
      <el-table-column
        v-if="columns.visible('confName')"
        :show-overflow-tooltip="true"
        prop="confName"
        label="配置英文标识"
        min-width="150"
      />
      <el-table-column
        v-if="columns.visible('valueType')"
        key="valueType"
        :show-overflow-tooltip="true"
        label="输入类型"
        prop="valueType"
        :filters="filterValueTypeDict"
        filter-placement="bottom-end"
        :filter-multiple="false"
        column-key="valueType"
        :filter-method="filterValueType"
      >
        <template slot-scope="scope">
          {{ valueTypeFormatter(scope.row.valueType) }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('confValue')"
        :show-overflow-tooltip="true"
        prop="confValue"
        label="默认值"
        min-width="150"
      />
      <el-table-column
        v-if="columns.visible('showSort')"
        :show-overflow-tooltip="true"
        label="排序值"
        prop="showSort"
      />
      <el-table-column
        v-if="columns.visible('status')"
        key="status"
        :show-overflow-tooltip="true"
        label="配置状态"
        prop="status"
        :filters="filterdataStatusDict"
        filter-placement="bottom-end"
        :filter-multiple="false"
        column-key="status"
        :filter-method="filterStatus"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            active-value="ENABLE"
            inactive-value="DISABLE"
            @change="changeEnabled(scope.row, scope.row.status)"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="columns.visible('upUserName')"
        :show-overflow-tooltip="true"
        label="更新人"
        prop="upUserName"
      />
      <el-table-column
        v-if="columns.visible('upTs')"
        label="更新时间"
        prop="upTs"
        min-width="150"
      />
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import sourceConfTemplateApi from '@/api/metadata/sourceConfTemplate'
import { isCode } from '@/utils/validate'

// crud交由presenter持有
const defaultCrud = CRUD({ title: '用户', url: 'api/sourceConfTemplate', crudMethod: { ...sourceConfTemplateApi }})
const defaultForm = {
  pkId: null,
  confType: null,
  confName: null,
  confLabel: null,
  defaultValue: null,
  isMain: 'Y',
  confDes: null,
  showSort: '1',
  valueType: 'INPUT',
  verifyRules: null,
  isShow: 'Y',
  isRelevance: 'N',
  isPlaceholderAttribute: 'N',
  relevanceConfName: null,
  relevanceConfValue: [],
  placeholderConfName: null,
  status: 'ENABLE'
}
export default {
  name: 'Project',
  components: { crudOperation, rrOperation, pagination },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['data_status', 'source_type', 'source_conf_value_type', 'verify_rules'],
  data() {
    var validateConfLabel = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入配置名称'))
      }
      const param = {
        'confLabel': value,
        'confType': this.form.confType
      }
      sourceConfTemplateApi.findListByPage(param).then(data => {
        if (data.total > 0) {
          for (var i = 0; i < data.content.length; i++) {
            if (data.content[i].confLabel === value && data.content[i].pkId !== this.form.pkId) {
              callback(new Error('配置名称已经存在！'))
            }
          }
          callback()
        } else {
          callback()
        }
      })
    }
    var validateConfName = (rule, value, callback) => {
      if (value === '' || value === null || value === undefined) {
        callback(new Error('请输入配置英文标识'))
      }
      if (!isCode(value)) {
        callback(new Error('配置英文标识只能输入英文字母、数字、下划线'))
      }
      const param = {
        'confName': value,
        'confType': this.form.confType
      }
      sourceConfTemplateApi.findListByPage(param).then(data => {
        if (data.total > 0) {
          for (var i = 0; i < data.content.length; i++) {
            if (data.content[i].confName === value && data.content[i].pkId !== this.form.pkId) {
              callback(new Error('配置英文标识已存在'))
            }
          }
          callback()
        } else {
          callback()
        }
      })
    }
    return {
      dialogVisible: false,
      assAttrList: [],
      attributeValue: [],
      permission: {
        add: ['sourceConnTemplate:add'],
        edit: ['sourceConnTemplate:edit'],
        del: ['sourceConnTemplate:del']
      },
      rules: {
        confType: [{ required: true, message: '请选择数据源类型', trigger: 'blur' }],
        confName: [{ required: true, validator: validateConfName, min: 0, max: 100, trigger: 'blur' }],
        confLabel: [{ required: true, validator: validateConfLabel, trigger: 'blur' }],
        valueType: [{ required: true, message: '请选择输入类型', trigger: 'blur' }],
        selectValues: [{ required: true, message: '请输入选择值', trigger: 'blur' }],
        showSort: [{ required: true, message: '请输入排序序号', trigger: 'blur' }],
        placeholderConfName: [{ required: true, message: '请选择所属占位符属性', trigger: 'blur' }],
        relevanceConfName: [{ required: true, message: '请选择关联属性名称', trigger: 'blur' }],
        relevanceConfValue: [{ required: true, message: '请选择关联属性值', trigger: 'blur' }],
        verifyRules: [{ required: true, message: '请选择关联属性值', trigger: 'blur' }],
        confDes: [{ required: false, message: '限制100个字符以内', min: 0, max: 100, trigger: 'blur' }]
      },
      dataStatusDict: [],
      filterdataStatusDict: [],
      confTypeDict: [],
      filterConfTypeDict: [],
      valueTypeDict: [],
      filterValueTypeDict: []
    }
  },
  watch: {
    dataStatusDict() {
      this.$nextTick(() => {
        this.dataStatusDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.filterdataStatusDict.push(obj)
        })
      })
    },
    confTypeDict() {
      this.$nextTick(() => {
        this.confTypeDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.filterConfTypeDict.push(obj)
        })
      })
    },
    valueTypeDict() {
      this.$nextTick(() => {
        this.valueTypeDict.forEach(item => {
          var obj = {
            text: item.label,
            value: item.value
          }
          this.filterValueTypeDict.push(obj)
        })
      })
    }
  },
  created() {
    this.crud.resetQuery(false)
    this.crud.optShow.download = false
    this.dataStatusDict = this.dict.data_status
    this.confTypeDict = this.dict.source_type
    this.valueTypeDict = this.dict.source_conf_value_type
  },
  methods: {
    rowDbclick() {
      this.dialog = true
    },
    [CRUD.HOOK.beforeSubmit](crud) {
      crud.form.relevanceConfValue = JSON.stringify(crud.form.relevanceConfValue)
    },
    [CRUD.HOOK.beforeToEdit](crud, form) {
      const relevanceConfValue = JSON.parse(form.relevanceConfValue)
      form.relevanceConfValue = relevanceConfValue
      this.associationAttribute()
    },
    filterValueType(value, row) {
      return row.valueType === value
    },
    filterConfType(value, row) {
      return row.confType === value
    },
    filterStatus(value, row) {
      return row.status === value
    },
    filterisMain(value, row) {
      return row.isMain === value
    },
    filterServiceType(value, row) {
      return row.serviceType === value
    },
    dataStatusFormatter(val) {
      return this.dict.label.data_status[val]
    },
    confTypeFormatter(val) {
      return this.dict.label.source_type[val]
    },
    valueTypeFormatter(val) {
      return this.dict.label.source_conf_value_type[val]
    },
    changeConfType() {
      this.form.relevanceConfName = null
      this.form.relevanceConfValue = null
      this.form.placeholderConfName = null
      this.associationAttribute()
    },
    associationAttribute() {
      this.assAttrList = []
      const params = {
        confType: this.form.confType,
        size: 1000
      }
      sourceConfTemplateApi.findListByPage(params).then(res => {
        this.assAttrList = res.content
      })
    },
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.data_status[val] + '" ' + data.confLabel + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sourceConfTemplateApi.edit(data).then(res => {
          this.crud.notify(this.dict.label.data_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.status = (data.status === 'ENABLE') ? 'DISABLE' : 'ENABLE'
        })
      }).catch(() => {
        data.status = (data.status === 'ENABLE') ? 'DISABLE' : 'ENABLE'
      })
    },
    changeRelevanceConfName(val) {
      this.form.relevanceConfValue = []
      this.attributeValue = []
      this.assAttrList.forEach(item => {
        if (item.confName === val) {
          this.attributeValue = JSON.parse(item.selectValues)
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .el-form-item{
   margin-top: 5px;
  }
  .el-checkbox{
    margin-left: 5px;
  }
</style>
